package com.shop.shop_end.controller;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mchange.lang.LongUtils;
import com.shop.shop_end.dto.EditPwdDto;
import com.shop.shop_end.entity.Admin;
import com.shop.shop_end.entity.User;
import com.shop.shop_end.exception.ServiceException;
import com.shop.shop_end.mapper.AdminMapper;
import com.shop.shop_end.service.AdminService;
import com.shop.shop_end.service.UserService;
import com.shop.shop_end.utils.MD5Util;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import com.shop.shop_end.dto.LoginUser;
import com.shop.shop_end.variable.EnableVariable;
import com.shop.shop_end.variable.ErrorCodeEnum;
import com.shop.shop_end.vo.UserVo;
import org.apache.ibatis.annotations.Update;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController extends BaseController{
    final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Resource
    private AdminService adminService;
    @Resource
    private UserService userService;
    @Resource
    private AdminMapper adminMapper;

    private HttpServletRequest httpServletRequest;

    /**
     * 管理员登录
     * @param loginUser
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){
        System.out.println("loginUser: " + loginUser);
//        admin.setAvatar("../../static/pig.jpg");
        return adminService.login(loginUser);
    }

    /**
     * 管理员注册
     * @param admin
     * @return
     */
    @RequestMapping("/addAdmin")
    public Result register(@RequestBody Admin admin){
        System.out.println("admin: " + admin);
//        admin.setAvatar("../../static/pig.jpg");
        return adminService.addAdmin(admin);
    }

    /**
     * 获取所有管理员信息
     */
    @RequestMapping("/getAllAdminList")
    public Result getAllAdminList() {
        return adminService.getAllAdmins();
    }

    // 修改密码
    @RequestMapping("/editPwd")
    @Transactional
    public Result editPwd(@RequestBody EditPwdDto editPwdDto) {
        logger.info("editPwdDto==>{}", editPwdDto);
        Long id = editPwdDto.getId();
        Admin admin = adminService.getAdminById(id);
        if (admin == null){
            logger.info("该账号不存在");
            return ResultUtil.fail("该账号已不存在");
        }
        String password = admin.getPassword();
        String oldPassword = editPwdDto.getOldPassword();
        String newPassword = editPwdDto.getNewPassword();
        String rePassword = editPwdDto.getRePassword();
        //后端还需再校验一次密码
        if (!newPassword.equals(rePassword)){
            logger.info("两次密码不一致");
            return ResultUtil.fail("两次密码不一致");
        }
        logger.info("两次密码一致，开始判断旧密码是否正确");
        //加密旧密码oldPassword与数据库里的password进行对比 TODO
        String md5 = MD5Util.generateMD5(oldPassword);
        if (!password.equals(md5)){
            logger.info("旧密码错误");
            return ResultUtil.fail("旧密码错误");
        }
        logger.info("开始对新密码加密并修改数据库");
        //
        String newMdPwd = MD5Util.generateMD5(newPassword);
        admin.setPassword(newMdPwd);
        try {
            UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<Admin>()
                    .set("password", newMdPwd)
                    .eq("adminId", id);
            int update = adminMapper.update(null, updateWrapper);
            if (update == EnableVariable.UNABLE){
                logger.info("修改失败");
                return ResultUtil.fail("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("修改出现异常");
            return ResultUtil.fail("修改出现异常");
        }
        logger.info("修改成功");
        return ResultUtil.ok("修改成功", editPwdDto);
    }

    // 通过主键删除数据
    @RequestMapping("deleteAdminById/{id}")
    public Result deleteAdminById(@PathVariable("id") Long id) {
        return adminService.deleteAdmin(id);
    }

    /**
     * 修改信息
     * @param admin
     * @return
     */
    @RequestMapping("/updateAdmin")
    public Result updateAdmin(@RequestBody Admin admin){
        System.out.println("admin==>"+admin.toString());
        return adminService.updateAdmin(admin);
    }

    /**
     * 删除用户
     * @param userVo
     * @return
     */
    @PostMapping("/deleteUser")
    public Result deletePeople(@RequestBody UserVo userVo){
        System.out.println("userVo: " + userVo);
        return userService.deleteUserById(userVo.getUserId());
    }
//    /**
//     * 生成测试用户数据
//     * @param quantity
//     * @return
//     */
//    @RequestMapping("generateRandomUsers/{quantity}")
//    Result generateRandomUsers(@PathVariable("quantity") int quantity){
//        for (int i = 0; i < quantity; i++) {
//            User user = new User();
//            user.setUsername(RandomStringUtils.randomAlphabetic(8));
//            user.setPassword(RandomStringUtils.randomAlphanumeric(10));
//            user.setPhone(RandomStringUtils.randomNumeric(10));
//            user.setEmail(RandomStringUtils.randomAlphabetic(8) + "@hzp.com");
//            user.setGender((Math.random() < 0.5) ? "男" : "女");
//            user.setRole("user");
////            user.setAvatar("https://hzp.com/avatar.jpg");
//            user.setCreateTime(new Date());
//            user.setEnable(1);
//            Result res = userService.addOneUser(user);
//            if (res.getCode() != 200){
//                List<User> userList = userService.getAllUserList();
//                String desc = "数据生成中断，已生成【" + (i+1) + "】条数据";
//                ResultUtil.fail(desc, userList);
//            }
//        }
//        List<User> userList = userService.getAllUserList();
//        return ResultUtil.ok(userList);
//    }

//    @RequestMapping("addPeople")
//    public Result addPeople(@RequestBody UserVo userVo){
//        System.out.println("userVo: " + userVo);
//        userVo.setRole("user");
//        User person = new User();
//        person.setUsername(userVo.getUsername());
//        person.setCreateTime(userVo.getCreateTime());
//        person.setPassword(userVo.getPassword());
////        person.setAvatar("../../static/plane.png");
//        person.setCreateTime(new Date());
//        person.setGender(userVo.getGender());
//        person.setEmail(userVo.getEmail());
//        person.setEnable(1);
//        person.setPhone(userVo.getPhone());
//        return userService(person);
//    }

}
